package com.atguigu.flink.timeAndwindow;

import com.atguigu.flink.func.ClickSource;
import com.atguigu.flink.pojo.Event;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;

import java.time.Duration;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by 黄凯 on 2023/6/18 0018 14:39
 *
 * @author 黄凯
 * 永远相信美好的事情总会发生.
 * <p>
 * pv / uv
 */
public class Flink08_PvUv {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        SingleOutputStreamOperator<Event> ds = env.addSource(new ClickSource())
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<Event>forBoundedOutOfOrderness(Duration.ZERO)
                                .withTimestampAssigner(
                                        (event, ts) -> event.getTs()
                                )
                );
        ds.print("input");

        //需求: 求pv / uv
        // ACC: Tuple2<Long ,HashSet<String> > :
        //      Long : pv
        //      HashSet: uv
        ds.keyBy(
                event -> true
        ).window(
                TumblingEventTimeWindows.of(Time.seconds(10))
        ).aggregate(
                new AggregateFunction<Event, Tuple2<Long, Set<String>>, Double>() {
                    @Override
                    public Tuple2<Long, Set<String>> createAccumulator() {
                        return Tuple2.of(0L, new HashSet<>());
                    }

                    @Override
                    public Tuple2<Long, Set<String>> add(Event value, Tuple2<Long, Set<String>> accumulator) {
                        accumulator.f1.add(value.getUser());
                        accumulator.setField(accumulator.f0 + 1, 0);
                        return accumulator;
                    }

                    @Override
                    public Double getResult(Tuple2<Long, Set<String>> accumulator) {
                        return accumulator.f0.doubleValue() / accumulator.f1.size();
                    }

                    @Override
                    public Tuple2<Long, Set<String>> merge(Tuple2<Long, Set<String>> a, Tuple2<Long, Set<String>> b) {
                        return null;
                    }
                }
        ).print();

        env.execute();

    }

}
